package com.feihong.txgw.tx_model;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.feihong.txgw.inter.contract.shopcar.IShopCarContract;
import com.feihong.txgw.model.bean.shopcar.ShopcarOperateEntity;
import com.feihong.txgw.model.greendao.ShopCarGoodsModel;
import com.feihong.txgw.shopcar.listener.OnShopEditListener;
import com.feihong.txgw.utils.greendao.GreenDaoOperateHelper;
import com.feihong.txgw.utils.helper.RxHelper;
import com.feihong.txgw.utils.manage.RetrofitManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;

/**
 * @Author wangziheng
 * @ProjectName txgw_app
 * @ClassName ShopCarMainModel
 * @package com.feihong.txgw.tx_model
 * @data 2018/5/2 12:06
 * @Describe
 * @Change
 */
public class ShopCarMainModel implements IShopCarContract.IShopCarMainModel {

    private static final String UPDATE = "UPDATE";
    private static final String DEL = "DEL";
    public static ShopCarMainModel create(){
        return new ShopCarMainModel();
    }
    @Override
    public Observable getRecommendGoods() {
        return RetrofitManager.getInstance().getShopCarRecommedGoods("9","","1").compose(RxHelper.rxSchedulerHelper());
    }

    @Override
    public Observable editShopCarGoodsToService(List<ShopCarGoodsModel> changeGoodsList, OnShopEditListener onShopEditListener) {
        List<ShopcarOperateEntity> mKeyContent = new ArrayList<>();
        Map<String,String> mParams = new HashMap<>();
        if (changeGoodsList != null && changeGoodsList.size() > 0) {
            for (ShopCarGoodsModel item : changeGoodsList) {
                if(!TextUtils.isEmpty(item.getAction())){
                    ShopcarOperateEntity shopcarOperateEntity = new ShopcarOperateEntity();
                    shopcarOperateEntity.setAction(item.getAction());
                    shopcarOperateEntity.setNums(String.valueOf(item.getGoodsNum()));
                    shopcarOperateEntity.setSku_id(String.valueOf(item.getGoodsID()));
                    mKeyContent.add(shopcarOperateEntity);
                }
            }
        }
        mParams.put("content",mKeyContent.size() == 0 ? "" : JSON.toJSONString(mKeyContent));
        return RetrofitManager.getInstance().editShopCarGoodsToService(mParams).compose(RxHelper.rxSchedulerHelper());
    }

    @Override
    public Observable editShopCarGoodsToLocal(String editType, List<ShopCarGoodsModel> changeGoodsList) {
        if (UPDATE.equals(editType)) {
            for (ShopCarGoodsModel dbGoodsCartModel : changeGoodsList) {
                GreenDaoOperateHelper.updateGoods(dbGoodsCartModel);
            }
        } else if (DEL.equals(editType)) {
            for (ShopCarGoodsModel dbGoodsCartModel : changeGoodsList) {
                GreenDaoOperateHelper.delModel(dbGoodsCartModel);
            }
        }
        return null;
    }
}
